import React, { useEffect, useState } from 'react'
import './Recently_opened.scss'
import zuijindakai from '../../../public/Recently_opened/最近打开.jpg'
import { useNavigate } from 'react-router-dom'

function Recently_opened() {
  const navigate = useNavigate() 
  const [recentItems, setRecentItems] = useState<any[]>([])
  const [isLoggedIn, setIsLoggedIn] = useState(false)

  useEffect(() => {
    const token = localStorage.getItem('token')
    setIsLoggedIn(!!token)
    
    if(token) {
      // 修复点：正确处理空值情况
      const userInfoString = localStorage.getItem('userInfo') || ''
      let userId: string | null = null
      
      try {
        // 只有非空字符串时才尝试解析
        if (userInfoString) {
          const userInfo = JSON.parse(userInfoString)
          userId = userInfo?.id || null
        }
      } catch (error) {
        console.error('解析用户信息失败:', error)
      }

      if(userId) {
        try {
          // 修复点：处理空值或无效JSON
          const recentDataString = localStorage.getItem(`recentItems_${userId}`) || '[]'
          const parsedData = JSON.parse(recentDataString)
          setRecentItems(Array.isArray(parsedData) ? parsedData : [])
        } catch (error) {
          console.error('解析最近打开记录失败:', error)
          setRecentItems([])
        }
      }
    }
  }, [])
   
  const handleViewMore = () => {
    if (!isLoggedIn) {
      navigate({
        pathname: '/',
        search: '?showLogin=true&redirect=/profile'
      })
    } else {
      navigate('/profile?tab=recent')
    }
  }
     
  return (
    <div className='opened-box'>
      <p>
        <h2 style={{ marginTop: '40px' }}>最近打开</h2> 
        <span className='gengduo' onClick={handleViewMore}>
          更多 &gt;
        </span>
      </p>
      <div className='opened-div'>
        {!isLoggedIn ? (
          <>
            <dt><img src={zuijindakai} alt="" className='opened-img' /></dt>
            <span className='opened-span'>登录后即可查看最近打开记录</span>
          </>
        ) : recentItems.length === 0 ? (
          <span className='opened-span'>空空如也</span>
        ) : (
          <div className="recent-items-container">
            {recentItems.slice(0, 4).map((item, index) => (
              <div key={index} className="recent-item">
                <img 
                  src={item.img} 
                  alt={item.title} 
                  onClick={() => navigate(item.link || '/')}
                />
                <div className="item-title">{item.title}</div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}

export default Recently_opened